<template>
  <div style="margin-top:20px;">
    <!-- <el-divider></el-divider> -->
    <el-form :inline="true"
             class="coverage-style-searchForm">
      <el-form-item>
        <div class="demo-input-suffix">
          <el-input prefix-icon="el-icon-search"
                    clearable
                    placeholder="请输入模板名称"
                    v-model="setNoticeTMPName">
          </el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <button @click="handleSearchData"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn">
          查询
        </button>
      </el-form-item>
      <el-form-item class="fr">
        <button @click="createForm()"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn">
          新建通知设置
        </button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-table class="table-td"
                ref="multipleTable"
                stripe
                border
                :header-cell-style="{ background: '#F2F3F8' }"
                :data="tableData"
                @select="pinSelect"
                v-loading="loading"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         align="center"
                         min-width="10%"></el-table-column>
        <el-table-column label="通知条件"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">
            <span style="color: #2393f1">{{ scope.row.dictName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{
            scope.row.workOrderTypeName
          }}</template>
        </el-table-column>
        <el-table-column label="状态"
                         min-width="15%"
                         align="center">
          <template slot-scope="scope">{{
            scope.row.status == 1 ? "启用" : "停用"
          }}</template>
        </el-table-column>
        <el-table-column label="创建时间"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>
        <el-table-column label="创建人"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{ scope.row.creatorName }}</template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         min-width="35%"
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text"
                       size="mini"
                       class="run-and-stop"
                       @click="handleChange(scope.$index, scope.row)">
              <!-- <i class="el-icon-circle-check"></i> -->
              <span v-if="scope.row.status !== 1">
                <img src="../../../assets/images/start.png"
                     alt />启用
              </span>
              <span v-else>
                <img src="../../../assets/images/stop.png"
                     alt />停用
              </span>
            </el-button>
            <el-button icon="el-icon-delete"
                       type="text"
                       size="mini"
                       class="btn"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button icon="el-icon-edit"
                       type="text"
                       size="mini"
                       class="btn"
                       @click="
                handleEdit(scope.$index, scope.row, { name: '编辑通知设置' })
              ">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="paging-foot page-foot-spacing"
            :gutter="20">
      <el-col :span="12">
        <span class="color-select">批量操作</span>
        <span class="select-number">（已选中{{ selectAllIdLength }}条）</span>
        <button @click="deleteBatch"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn">
          删除
        </button>
      </el-col>
      <el-col :span="12">
        <div>
          <el-pagination background
                         class="el-pagination-style"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="page"
                         :page-sizes="[10, 20, 50, 100]"
                         :page-size="pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="totalDataLength"></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  NoticeTempList,
  NoticeTempListById,
  NoticeTempListForbidden,
  NoticeTempListUpdate,
  NoticeTempListDelete,
} from "@/api/setNotice";
import newSetNotice from "./newSetNotice";
import common from "@/common/common.js";
export default {
  data () {
    return {
      lists: [],
      changeLists: [],
      origin: -1,
      pin: false,
      setNoticeTMPName: "",
      selectAllId: [],
      selectAllIdLength: 0,
      page: 1,
      pageSize: 10,
      pageNumber: "",
      tableData: [],
      totalDataLength: 0,
    };
  },
  components: {
    newSetNotice,
  },
  mounted () {
    // 列表查询
    this.handleSearch();
    window.addEventListener('keydown', code => { // 这个是获取键盘按住事件
      // console.log(code) // 这个是你按住键盘打印出键盘信息，在浏览器中自行查看
      if (code.keyCode === 16 && code.shiftKey) { // 判断是否按住shift键，是就把pin赋值为true
        this.pin = true
      }
    })
    window.addEventListener('keyup', code => { // 这个是获取键盘松开事件
      if (code.keyCode === 16) { // 判断是否松开shift键，是就把pin赋值为false
        this.pin = false
        if (this.lists.length > 2) {
          this.selectAllId = this.lists
        } else {
          this.selectAllId = this.changeLists
        }
        this.selectAllIdLength = this.selectAllId.length
      }
    })
  },
  destroyed () {
    window.removeEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true
      }
    }, false)
    window.removeEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false
      }
    }, false)
  },
  methods: {
    // 这里是select事件开始
    pinSelect (item, row) {
      const data = this.tableData // 获取所有数据
      const origin = this.origin // 起点数 从-1开始
      const endIdx = row.index // 终点数
      if (this.pin && item.includes(data[origin])) { // 判断按住
        // this.$refs.multipleTable.selectClear()
        const sum = Math.abs(origin - endIdx) + 1// 这里记录终点
        const min = Math.min(origin, endIdx)// 这里记录起点
        let i = 0

        while (i < sum) {
          const index = min + i
          this.$refs.multipleTable.toggleRowSelection(data[index], true) // 通过ref打点调用toggleRowSelection方法，第二个必须为true
          i++
        }
        this.lists = this.selectAllId
      } else {
        this.origin = row.index // 没按住记录起点或没选起点
        this.lists = []
      }
    },
    handleSizeChange (val) {
      this.pageSize = val;
      this.handleSearchData();
    },
    handleCurrentChange (val) {
      this.page = val
      this.handleSearchData();
    },
    // 编辑
    handleEdit (index, row, params) {
      console.log("////////////***//////////", row.id);
      this.$store.commit("setNoticeFun", row.id);
      this.$router.push("/newSetNotice");
    },
    // 删除
    handleDelete (index, row) {
      this.deleteSelect([row.id]);
    },
    // 新建
    createForm () {
      let row = "";
      this.$store.commit("setNoticeFun", row);
      this.$router.push("/newSetNotice");
    },
    // 启用停用
    handleChange (index, row) {
      let status = row.status;
      if (status === 0) {
        status = 1;
      } else {
        status = 0;
      }
      let params = {
        status: status,
        id: row.id,
      };
      NoticeTempListForbidden(params).then((res) => {
        let data = res.data;
        if (data.retCode === 200) {
          this.$message({
            type: "success",
            message: data.msg,
          });
          this.handleSearch();
        } else {
          this.$message({
            type: "error",
            message: data.msg,
          });
        }
      });
    },
    // 列表查询
    handleSearch () {
      this.handleSearchData();
    },
    // 列表查询
    handleSearchData () {
      let params = {
        pageNumber: this.page,
        pageSize: this.pageSize,
        searchContent: "" || this.setNoticeTMPName
      };
      NoticeTempList(params).then((res) => {
        let data = res.data;
        if (data.retCode === 200) {
          this.tableData = data.data;
          this.totalDataLength = data.count;
          this.origin = -1
          this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
        }
      });
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange (val) {
      this.selectAllIdLength = val.length;
      this.selectAllId = [];
      val.map((value, key, index) => {
        this.selectAllId.push(value.id);
      });
      this.changeLists = this.selectAllId
    },
    deleteBatch () {
      if (this.selectAllIdLength === 0) {
        this.$message({ message: "请选择删除项", type: "error" });
        return;
      }
      this.deleteSelect(this.selectAllId);
    },
    deleteSelect (idList) {
      let params = {
        ids: idList,
      };
      this.$confirm("确认要删除吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        customClass: "messageBox-prompt-delete",
      }).then(() => {
        NoticeTempListDelete(params).then((res) => {
          if (res.data.retCode === 200) {
            this.$message({ message: res.data.msg, type: "success" });
            this.handleSearchData();
          } else {
            this.$message({ message: res.data.msg, type: "error" });
          }
        });
      });
    },
    // 时间戳的转换
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp);
    },
  },
};
</script>
<style scoped>
.el-pagination-style {
  text-align: right;
}
>>> .el-button--text {
  line-height: 16px;
}
.select-number {
  color: #b50029;
  font-size: 13px;
  padding: 0 5px;
}
</style>
